<!-- 聊天消息 -->
<template>
  <div class="message-container">
    <van-nav-bar title="消息"
                 :left-arrow="false">
      <template #right>
        <van-icon name="search"
                  size="20"
                  color="inherit"
                  @click="navigatorSearch" />
      </template>
    </van-nav-bar>

    <!-- 聊天联系人列表 -->
    <van-swipe-cell v-for="(chatUserInfo, index) in chatUserInfos"
                    :key="index">
      <van-config-provider :theme-vars="themeVars">
        <van-cell-group>
          <van-cell clickable
                    @click="navigatorChat(chatUserInfo.identity)">
            <!-- 使用 title 插槽来自定义icon -->
            <template #icon>
              <van-badge :content="chatUserInfo.noReadMessageCount"
                         max="99">
                <div>
                  <van-image width="50"
                             height="50"
                             :src="chatUserInfo.avatar" />
                </div>
              </van-badge>
            </template>
            <!-- 使用 title 插槽来自定义标题 -->
            <template #title>
              <span class="title-lable-margin">{{chatUserInfo.realName}} </span>
              <van-icon name="friends-o" />
            </template>
            <!-- 使用 lable 插槽来自定义lable -->
            <template #label>
              <span v-if="chatUserInfo.lasterMessageContentType === 0"
                    class="title-lable-margin"
                    v-html="$filters.ellipsis(chatUserInfo.lasterMessage,10)"></span>
              <span v-if="chatUserInfo.lasterMessageContentType === 2"
                    class="title-lable-margin">【附件】</span>
            </template>
            <!-- 使用 lable 插槽来自定义lable -->
            <template #value>
              <span class="right-value">{{$filters.dataformat(Number(chatUserInfo.lasterCreateTime), "YYYY-MM-DD HH:mm:ss")}}</span>
              <div class="dot-badge">
                <van-badge dot
                           :color="chatUserInfo.online == 1? 'green':'#dcdee0'"> </van-badge>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-config-provider>

      <template #right>
        <van-button square
                    text="删除"
                    type="danger"
                    class="delete-button" />
      </template>
    </van-swipe-cell>

  </div>
</template>

<script>
import { Toast } from 'vant';
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  data () {
    //这里存放数据
    var themeVars = {
      cellLabelMarginTop: "0.20667rem",
    };
    return {
      themeVars,
      // 聊天联系人
      chatUserInfos: []
    };
  },
  //方法集合
  methods: {
    // 初始化聊天联系人
    init () {
      var that = this;
      that.$http
        .get(that.$reqPrefix.user + "/im/users/chat", {}).then(res => {
          this.chatUserInfos = res.data;
          //构建总线监听
          that.$emitter.on('onmessage', that.onmessage);
        }).catch(err => {
          Toast.fail(err.data.message)
        });
    },
    // 调到搜索页面
    navigatorSearch () {
      this.$router.push("/search");
    },
    // 跳转到聊天界面
    navigatorChat (identity) {
      this.$router.push({ name: "UserChat", params: { 'identity': identity } });
    },
    //总线回调函数
    onmessage: function (data) {
      // 如果接收到的消息是好友添加，则做相应处理，计数加1

      if (data.messageType === SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_BROADCAST) {
        var from = data.message.getFrom();
        var content = data.message.getContent();
        if (content === 'online' || content === 'offline') {
          // 遍历现有联系人，进行状态改变
          for (let i = 0, len = this.chatUserInfos.length; i < len; i++) {
            if (this.chatUserInfos[i].identity === from) {
              this.chatUserInfos[i].online = content === 'online' ? 1 : 0;
              break;
            }

          }
        }
      }


      if (data.messageType === SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_P_CHAT) {
        var from = data.message.getFrom();
        var content = data.message.getContent();
        var createTime = data.message.getCreateTime();
        var isContain = false;
        // 遍历现有联系人，进行消息设置
        for (let i = 0, len = this.chatUserInfos.length; i < len; i++) {
          if (this.chatUserInfos[i].identity === from) {
            this.chatUserInfos[i].lasterMessage = content;
            this.chatUserInfos[i].lasterCreateTime = createTime;
            isContain = true;
            break;
          }

        }
        if (!isContain) {
          //追加数据并追加数据；

        }

      }
    },

  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.init();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  //生命周期 - 创建之前
  beforeCreate () { },
  //生命周期 - 挂载之前
  beforeMount () { },
  //生命周期 - 更新之前
  beforeUpdate () { },
  //生命周期 - 更新之后
  updated () { },
  //生命周期 - 销毁之前
  beforeUnmount () { },
  //生命周期 - 销毁完成
  unmounted () { //销毁监听
    this.$emitter.off('onmessage', this.onmessage);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated () { },
};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类
.message-container {
  position: relative;
  background: whitesmoke;
}

.delete-button {
  height: 100%;
}

.title-lable-margin {
  margin-left: 10px;
}
</style>
